package cn.fulong.sso.client.manager.impl;


import cn.fulong.sso.client.manager.AbstractSessionManager;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;
import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @desc: 单机环境下SessionManger实现
 * @author: 云树
 * @createDate: 2019/1/17 10:24
 * @version: 1.0
 */
@Slf4j
public class ConcurrentHashMapSessionManager extends AbstractSessionManager {

    /**
     * token 映射 HttpSession 会话存储
     */
    private final ConcurrentHashMap<String, WeakReference<HttpSession>> tokenMappingSession = new ConcurrentHashMap();

    @Override
    public boolean removeSessionManagerByToken(String token) {
        WeakReference<HttpSession> weakReference = tokenMappingSession.get(token);
        if (weakReference != null) {
            HttpSession session = weakReference.get();
            try {
                session.invalidate();
            } catch (Exception e) {
                log.error("【ConcurrentHashMapSessionManager】根据token(" + token + ")清除会话", e);
            }
        }
        this.removeTokenMappingSessionByToken(token);
        return true;
    }

    @Override
    public boolean addTokenSessionStorage(String token, HttpSession sessionStorage) {
        tokenMappingSession.put(token, new WeakReference<HttpSession>(sessionStorage));
        return true;
    }


    @Override
    public boolean removeTokenMappingSessionByToken(String token) {
        if(token != null) {
            tokenMappingSession.remove(token);
        }
        return true;
    }
}
